package com.hd.manager.task.StudentInfotask;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hd.appcommon.entity.Student;
import com.hd.appcommon.entity.User;
import com.hd.appcommon.entity.dto.XGSaasStuRecord;
import com.hd.appcommon.entity.dto.XGSaasTeacherRecord;
import com.hd.appcommon.service.StudentService;
import com.hd.appcommon.service.UserService;
import com.hd.hdxgddcommon.utils.StringUtils;
import com.hd.manager.config.URLConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.hd.appcommon.utils.SecretUtils.encrypt;
import static com.hd.manager.util.SensitiveMessageUtil.getXGSaasSensitive;
import static com.hd.manager.util.SensitiveMessageUtil.getXGSaasToken;


/**
 * @author: hzp
 * @date: 2022/5/2
 * @description:
 */
//@Component
//1.主要用于标记配置类，兼备Component的效果。
//@Configuration
//// 2.开启定时任务
//@EnableScheduling
//@Configuration
//// 2.开启定时任务
//@EnableScheduling
@Component
@Slf4j
/**
 * 当前仅被测试方法调用
 * */
public class SensitiveMessageTask {

    @Autowired
    UserService userService;
    @Autowired
    StudentService studentService;

    /**
     * 学生敏感信息接口和教工敏感信息接口就行了。
     * <p>
     * AppKey：6271d6c6e4b099de5d2bb6df
     * AppSecret：-E1PZNvU4fy81I6PAG0sJMQ3wcqu1Lm_Q_EAwF78awj9fxpndtTydLr8E1EFpbwE
     * <p>
     * https://www.yuque.com/docs/share/5e3fe832-01d0-4314-99f5-5026d34e2385?《杭电信工-数据中心开放接口 RESTful APIs》密码：xm4q
     */
//    @Scheduled(cron = "0 0 1 11 * ?")
    public void syncTeachersIDCard() {

        log.info("syncTeachersIDCard task start");
        // 1. 请求远端,获得token
        String xgSaasToken = getXGSaasToken();
        // 2. 根据token 请求教师敏感信息接口
        // 保存总page数目
        int pages = 1;
        int page = 1;
        JSONObject data;
        do {
            JSONObject xgSaasTeacherSensitive = getXGSaasSensitive(URLConstant.URL_XGSAAS_TSENSITIVE_GET, xgSaasToken, page, 1000);
            System.out.println("sensitiveMessage:");
            System.out.println(xgSaasTeacherSensitive.toJSONString());
            // 解析获得数据和 pages
            if (xgSaasTeacherSensitive != null && xgSaasTeacherSensitive.getBoolean("success")) {
                data = xgSaasTeacherSensitive.getJSONObject("data");
                if (pages == 1) {
                    // 第一次需要赋值
                    pages = data.getInteger("pages");
                }

                // 解析数据进行更新
                List<XGSaasTeacherRecord> records = JSONArray.parseArray(data.getString("records"), XGSaasTeacherRecord.class);

                List<Student> students = new ArrayList<>();

                List<User> users = records.stream().map(record -> {
                    User user = new User();
                    //姓名 name
                    user.setName(record.getXM());
                    //电话 phone
                    user.setPhone(record.getYDDH());
                    //工号 job_number（compulsory!）
                    user.setJobNumber(record.getJGH());
                    //性别 gender
                    user.setGender(record.getXB().equals("1")?0:1);
                    //身份证号 card_id
                    user.setCardId(record.getSFZH());
                    //密码 password
                    user.setPassword(encrypt(record.getJGH()));
                    //创建时间 create_time（新）
                    user.setCreateTime(new Date());
                    //更改时间 modify_time（新）
                    user.setModifyTime(new Date());
                    //类型 type (教师 2)
                    user.setType(2);
                    return user;
                }).collect(Collectors.toList());
                List<User> insertUsers = new ArrayList<>();
                for(int i = 0, len = users.size(); i < len; i++){
                    if(!exist(users.get(i))){
                        insertUsers.add(users.get(i));
                        users.remove(i);
                        len--;
                        i--;
                    }
                }
                // 自己批量更新
                userService.updateBatchByQueryWrapper(users, user -> new QueryWrapper<User>().eq("job_number", user.getJobNumber()));
                //批量插入
                userService.saveBatch(insertUsers);
            }
            page++;
        } while (pages >= page);
    }

    public boolean exist(User user){
        if(null!=userService.getOne(new QueryWrapper<User>().eq("job_number",user.getJobNumber()).last("limit 1"))){
            return true;
        }
        else return false;
    }

//    @Scheduled(cron = "0 0 1 11 * ?")
    public void syncStudentsIDCard() {
        log.info("syncStudentsIDCard task start");
        // 1. 请求远端,获得token
        String xgSaasToken = getXGSaasToken();
        // 2. 根据token 请求学生敏感信息接口
        // 保存总page数目
        int pages = 1;
        int page = 1;
        JSONObject data;

        // 获得当前年份 - 5 年
        int year = LocalDate.now().getYear() - 5;

        do {
            JSONObject xgSaasStuSensitive = getXGSaasSensitive(URLConstant.URL_XGSAAS_SSENSITIVE_GET, xgSaasToken, page, 1000);
            System.out.println(xgSaasStuSensitive.toJSONString());
            // 解析获得数据和 pages
            if (xgSaasStuSensitive != null && xgSaasStuSensitive.getBoolean("success")) {
                data = xgSaasStuSensitive.getJSONObject("data");
                if (pages == 1) {
                    // 第一次需要赋值
                    pages = data.getInteger("pages");
                }

                // 解析数据进行更新
                List<XGSaasStuRecord> records = JSONArray.parseArray(data.getString("records"), XGSaasStuRecord.class);
                // 过滤掉之前五年前入学的人,不需要了
                List<XGSaasStuRecord> collect = records.stream().filter(r -> {
                    String jbny = r.getJBNY();
                    return Integer.parseInt(jbny) >= year;
                }).collect(Collectors.toList());
                // 如果都被过滤了不需要操作数据库
                if (collect.isEmpty()) {
                    page++;
                    continue;
                }


                List<User> users = collect.stream().map(record -> {
                    User user = new User();
                    //姓名 name
                    user.setName(record.getXM());
                    //电话 phone
                    user.setPhone(record.getYDDH());
                    //学号 job_number（compulsory!）
                    user.setJobNumber(record.getXH());
                    //性别 gender 返回信息1代表女 0代表男 数据库刚好相反
                    user.setGender(record.getXB().equals("1")?0:1);
                    //身份证号 card_id
                    user.setCardId(record.getSFZH());
                    //密码 password
                    user.setPassword(encrypt(record.getXH()));
                    //创建时间 create_time（新）
                    user.setCreateTime(new Date());
                    //更改时间 modify_time（新）
                    user.setModifyTime(new Date());
                    //类型 type (学生 1)
                    user.setType(1);
                    return user;
                }).collect(Collectors.toList());

                List<User> insertUsers = new ArrayList<>();
                for(int i = 0, len = users.size(); i < len; i++){
                    if(!exist(users.get(i))){
                        insertUsers.add(users.get(i));
                        users.remove(i);
                        len--;
                        i--;
                    }
                }
                // 批量增加
                userService.saveBatch(insertUsers);
                // 自己批量更新
                userService.updateBatchByQueryWrapper(users, user -> new QueryWrapper<User>().eq("job_number", user.getJobNumber()));
            }
            page++;
        } while (pages >= page);
    }


    //    @Scheduled(cron = "0 10 1 * * ?")   //
//    @Scheduled(cron = "0 10 1 * * ?")
    public void testSync() {
        log.info("testSync  task start 1:10");

    }

//    @Scheduled(cron = "0 0 1 12 * ?")
//    public void syncPersonInfo() {
//        log.info("syncPersonInfo task start");
//        List<Student> students = studentService.list();
//
//        List<PersonBasicInfo> basicStuInfoList = students.parallelStream().map(student -> {
//            PersonBasicInfo personBasicInfo = new PersonBasicInfo();
//            personBasicInfo.setUserId(student.getUserId());
//            personBasicInfo.setName(student.getName());
//            personBasicInfo.setSno(student.getSno());
//            personBasicInfo.setPhone(student.getPhone());
//            if (StringUtils.isNotEmpty(student.getSfz())) {
//                personBasicInfo.setIdcard(student.getSfz().trim());
//                String s = judgeGender(student.getSfz().trim());
//                personBasicInfo.setGender(s);
//            }
//
//            personBasicInfo.setType("2");
//            // 通过身份证判定
//            return personBasicInfo;
//        }).collect(Collectors.toList());
//
//        List<Teacher> teachers = teacherService.list();
//
//        List<PersonBasicInfo> basicTeacherInfoList = teachers.parallelStream().map(teacher -> {
//            PersonBasicInfo personBasicInfo = new PersonBasicInfo();
//            personBasicInfo.setUserId(teacher.getUserId());
//            personBasicInfo.setName(teacher.getName());
//            personBasicInfo.setPhone(teacher.getPhone());
//            personBasicInfo.setPhone(teacher.getPhone());
//            personBasicInfo.setType("1");
//            // 通过身份证判定
//            if (StringUtils.isNotEmpty(teacher.getSfz())) {
//                personBasicInfo.setIdcard(teacher.getSfz().trim());
//                personBasicInfo.setGender(judgeGender(teacher.getSfz().trim()));
//            }
//            return personBasicInfo;
//        }).collect(Collectors.toList());
//
//        basicStuInfoList.addAll(basicTeacherInfoList);
//        personBasicInfoService.saveOrUpdateBatch(basicStuInfoList);
//
//    }

    public String judgeGender(String idCard) {
        if (StringUtils.isEmpty(idCard)) {
            return "男";
        }

        int substring = Integer.parseInt(idCard.substring(16, 17));
        return substring % 2 == 0 ? "女" : "男";
    }

}
